//
//  STRegisterGetCodeView.swift
//  iPhone
//
//  Created by Toj on 4/24/23.
//

import UIKit

protocol STRegisterGetCodeViewDelegate: NSObjectProtocol {
    func registerGetCodeViewDidTapClose(_ getcodeView: STRegisterGetCodeView)
    func registerGetCodeViewDidTapGetcode(_ getcodeView: STRegisterGetCodeView)
    func registerGetCodeViewDidInputFinished(_ getcodeView: STRegisterGetCodeView, code: String)
}

class STRegisterGetCodeView: UIView {
    
    weak var delegate: STRegisterGetCodeViewDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupMakeAddSubviews()
        setupMakeInitialize()
        setupMakeNotification()
        setupMakeLayoutSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /* 背景View */
    private lazy var backgroundView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.tt_alpha(0.5)
        
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(didTapBackground))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    /* 展示内容 */
    private lazy var contentView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        view.cm_corner(radius: 24, corners: [.layerMinXMinYCorner, .layerMaxXMinYCorner])
        
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(didTapEndEditing))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    /* 返回按钮 */
    private lazy var backButton: UIButton = {
        let view = UIButton()
        view.setImage("com_signin_back_icon".img_resource, for: .normal)
        view.addTarget(self, action: #selector(didTapClosed), for: .touchUpInside)
        return view
    }()
    
    /* 标题 */
    private lazy var titleLabel: UILabel = {
        let view = UILabel()
        view.textColor = "#333333".to_color
        view.font = 20.to_boldFont
        view.textAlignment = .center
        view.numberOfLines = 0
        view.text = "NewSignIn_Code".localized()
        return view
    }()
    
    /* 选择国家 */
    private lazy var countryImageView: UIImageView = {
        let view = UIImageView()
        view.image = "com_country_others".img_resource
        return view
    }()
    private lazy var arrowImageView: UIImageView = {
        let view = UIImageView()
        view.image = "com_arrow_down".img_resource
        return view
    }()
    private lazy var countryView = UIView()
    
    /* 账号 */
    private(set) lazy var accountLabel: UILabel = {
        let view = UILabel()
        view.textColor = .black
        view.font = 14.to_boldFont
        return view
    }()
    
    /* account Line */
    private lazy var accountLineView: UIView = {
        let view = UIView()
        view.backgroundColor = "#999999".to_color
        return view
    }()
    
    /* codes */
    private lazy var codesView = STVerifyCodeView.init(inputTextNum: 4)

    /* GET CODE */
    private lazy var getCodeButton: UIButton = {
        let view = UIButton()
        view.backgroundColor = "#0087EB".to_color
        view.titleLabel?.font = 14.to_boldFont
        view.setTitleColor(.white, for: .normal)
        view.setTitle("get_code".localized(), for: .normal)
        
        view.frame = CGRect(origin: .zero, size: CGSize(width: 88, height: 32.ui_scale))
        view.addTarget(self, action: #selector(didTapGetCode), for: .touchUpInside)
        view.cm_cornerRadius = 16.ui_scale
        return view
    }()
}

// MARK: - 点击事件
@objc private extension STRegisterGetCodeView {
    
    func didTapBackground() {
        didTapClosed()
    }
    
    func didTapClosed() {
        print("-->toj: func:" + #function)
        didTapEndEditing()
        delegate?.registerGetCodeViewDidTapClose(self)
    }
    
    func didTapGetCode() {
        print("-->toj: func:" + #function)
        didTapEndEditing()
        delegate?.registerGetCodeViewDidTapGetcode(self)
    }
    
    func didTapEndEditing() {
        endEditing(true)
    }
    
    func keyboardWillShow(notification: Notification) {
        guard let info = notification.userInfo as NSDictionary?
        else { return }
        
        let frameValue = info[UIResponder.keyboardFrameEndUserInfoKey]
        // 得到键盘frame
        let keyboardFrame = (frameValue as AnyObject).cgRectValue
        let kbHeight = keyboardFrame?.size.height ?? 303
        
        let kbDuration = info[UIResponder.keyboardAnimationDurationUserInfoKey]
        let duration = kbDuration as? TimeInterval ?? 0.25
        
        setupMakeLayoutContentView(kbHeight)
        
        UIView.animate(withDuration: duration) {
            self.layoutIfNeeded()
        }
    }
    
    func keyboardWillHide(notification: Notification) {
        guard let info = notification.userInfo as NSDictionary?
        else { return }
        
        let kbDuration = info[UIResponder.keyboardAnimationDurationUserInfoKey]
        let duration = kbDuration as? TimeInterval ?? 0.25
        
        setupMakeLayoutContentView()
        
        UIView.animate(withDuration: duration) {
            self.layoutIfNeeded()
        }
    }
}

// MARK: - Public
extension STRegisterGetCodeView {
    
    func show() {
        codesView.cleanCodes()
        isHidden = false
        setNeedsLayout()
    }
    
    func hide() {
        isHidden = true
    }
}

// MARK: - Private
private extension STRegisterGetCodeView {
    
    func inputFinish(string code: String) {
        delegate?.registerGetCodeViewDidInputFinished(self, code: code)
    }
}

// MARK: - 初始化设置
private extension STRegisterGetCodeView {
    
    func setupMakeAddSubviews() {
        
        addSubview(backgroundView)
        
        addSubview(contentView)
        
        // 标题
        contentView.addSubview(titleLabel)
        // 关闭按钮
        contentView.addSubview(backButton)
        // 国家
        contentView.addSubview(countryView)
        countryView.addSubview(countryImageView)
        countryView.addSubview(arrowImageView)
        
        // 账号
        contentView.addSubview(accountLabel)
        // 账号下面的横线
        contentView.addSubview(accountLineView)
        
        // 验证码
        contentView.addSubview(codesView)
        
        // 获取验证码
        contentView.addSubview(getCodeButton)
    }
    
    func setupMakeLayoutContentView(_ margin: CGFloat = 0) {
        print("-->toj: margin:\(margin)")
        contentView.snp.remakeConstraints { make in
            make.left.right.equalTo(self)
            make.height.equalTo(286.ui_mscale)
            make.bottom.equalTo(-margin)
        }
    }
    
    func setupMakeLayoutSubviews() {
        
        backgroundView.snp.makeConstraints { make in
            make.edges.equalTo(self)
        }
        setupMakeLayoutContentView()
        backButton.snp.makeConstraints { make in
            make.left.top.equalTo(contentView)
            make.width.equalTo(48)
            make.height.equalTo(48)
        }
        titleLabel.snp.makeConstraints { make in
            make.left.right.equalTo(contentView).inset(20)
            make.top.equalTo(contentView)
            make.height.equalTo(100.ui_mscale)
        }
        
        countryView.snp.makeConstraints { make in
            make.left.equalTo(24)
            make.width.equalTo(48)
            make.height.equalTo(30)
            make.top.equalTo(titleLabel.snp.bottom)
        }
        countryImageView.snp.makeConstraints { make in
            make.left.centerY.equalTo(countryView)
            make.height.equalTo(24)
            make.width.equalTo(24)
        }
        arrowImageView.snp.makeConstraints { make in
            make.right.centerY.equalTo(countryView)
            make.height.equalTo(24)
            make.width.equalTo(24)
        }
        
        accountLabel.snp.makeConstraints { make in
            make.left.equalTo(countryView.snp.right).offset(12)
            make.right.equalTo(snp.right).offset(-26)
            make.height.equalTo(24)
            make.centerY.equalTo(countryView)
        }
        
        accountLineView.snp.makeConstraints { make in
            make.bottom.left.right.equalTo(accountLabel)
            make.height.equalTo(1)
        }
        
        let size = getCodeButton.frame.size
        getCodeButton.snp.remakeConstraints { make in
            make.right.equalTo(contentView).inset(24)
            make.top.equalTo(accountLineView.snp.bottom).offset(20.ui_mscale)
            make.width.equalTo(size.width)
            make.height.equalTo(size.height)
        }
        
        codesView.snp.makeConstraints { (make) in
            make.left.equalTo(24)
            make.right.equalTo(getCodeButton.snp.left).offset(-8)
            make.top.bottom.equalTo(getCodeButton)
        }
    }
    
    func setupMakeInitialize() {
        // 监听验证码输入的过程
        codesView.textValueChange = { code in
            print("-->toj: input string: \(code)")
        }
        
        // 监听验证码输入完成
        codesView.inputFinish = { [weak self] code in
            print("-->toj: finished string: \(code)")
            self?.inputFinish(string: code)
        }
    }
    
    func setupMakeNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
}
